var basePath="/";
var parentParams=artDialog.data('params');
var descEditor;
$(function(){
  $(".filedsUl .add").click(function(){
    artDialog.prompt("输入字段名(只能由汉字字母下划线组成，多个用逗号分隔)：", function(field){
      var reg = new RegExp("^\\s*[A-Za-z_\u4e00-\u9fa5]+\\s*([,，]\\s*[A-Za-z0-9_\u4e00-\u9fa5]+\\s*)*$");
      if(! reg.test(field)){
        artDialog.alert("字段名只能由汉字字母下划线组成，多个用逗号分隔");
        return false;
      }
      var keywords = ['id','cateId','infos','lng','lat','enabled','createTime','createUser','updateTime','updateUser','pager','pictures','pictureNames']
      var fields = [];
      $("select[name=field] option").each(function(){
        fields.push($(this).text());
      });
      var newFields = field.split(/[,，]/);
      var nf = [];
      for(var o in newFields){
        var f = newFields[o].replace(/\s*/g, "");
        if(fields.indexOf(f) != -1){
          artDialog.alert("字段名【"+f+"】已存在");
          return false;
        }
        if(keywords.indexOf(f) != -1){
          artDialog.alert("【"+f+"】是关键字，不能使用");
          return false;
        }
        fields.push(f);
        nf.push(f);
      }
      nf.forEach(function(field){
        $("select[name=field]").append('<option>'+field+'</option>');
      });
    }, "");
  });
  $(".filedsUl .del").click(function(){
    var options = $("select[name=field] option:selected");
    if(options.length==0){
      artDialog.alert("请选择要删除的字段(可多选)");
      return false;
    }
    options.remove();
  });
  $(".filedsUl .top").click(function(){
    var options = $("select[name=field] option:selected");
    if(options.length==0){
      artDialog.alert("请选择要置顶的字段(可多选)");
      return false;
    }
    $("select[name=field]").prepend(options.remove());
  });
  $(".filedsUl .bottom").click(function(){
    var options = $("select[name=field] option:selected");
    if(options.length==0){
      artDialog.alert("请选择要置尾的字段(可多选)");
      return false;
    }
    $("select[name=field]").append(options.remove());
  });
  $(".filedsUl .prev").click(function(){
    var options = $("select[name=field] option:selected");
    if(options.length==0){
      artDialog.alert("请选择要上移的字段(可多选)");
      return false;
    }
    $("select[name=field] option:selected:last").after($("select[name=field] option:selected:first").prev());  
  });
  $(".filedsUl .next").click(function(){
    var options = $("select[name=field] option:selected");
    if(options.length==0){
      artDialog.alert("请选择要下移的字段(可多选)");
      return false;
    }
    $("select[name=field] option:selected:first").before($("select[name=field] option:selected:last").next());  
  });
  var handle = new UtilsHandle({
    basePath: "/",
    uploadImages:{uploadFileId: 'uploadImage', multiple: false, items: [{
      data: {"mark": 0, "width": 16, "height": 16, "of": 1},
      uploadBtn: $('#uploadCateImgBtn'), 
      success: function (data, textStatus) {
        if(data.code==0){
          for(var o in data.data){
            var pic = data.data[o].original;
            $('#cateImgSpan').html('<img class="dataImg" width="16px" height="16px" src="'+pic+'" data="'+pic+'">'); 
          }
        }else{
          artDialog.alert(data.msg);
        }
      },
      complete: function (XMLHttpRequest, textStatus) {
        $('.close').unbind().click(function(){
          $(this).parent().remove();
        }); 
        $('.dataImg').unbind().click(function(){
          if($('#viewImg').length>0){ 
            $('#viewImg').remove(); 
          } 
          $('body').append('<img id="viewImg" style="display:none" src="'+$(this).attr("src")+'">');
          $('#viewImg').on("load", function(){
            var w=$(this).width();
            var h=$(this).height();
            var l = w / h;
            if(h > handle.getScreenHeight() * 0.85){
              h = handle.getScreenHeight() * 0.85;
              w = h * l;
            }
            artDialog.alert2('<div style="width:'+w+'px;height:'+h+'px;"><img style="height:'+h+'px" src="'+$(this).attr("src")+'">') 
          }); 
        }); 
      } 
    },{
      data: {"mark": 0, "maxWidth": 60, "maxHeight": 60, "of": 0},
      uploadBtn: $('#uploadOverImgBtn'), 
      success: function (data, textStatus) {
        if(data.code==0){
          for(var o in data.data){
            var pic = data.data[o].original;
            $('#overImgSpan').html('<span style="position: relative;"><img class="dataImg" width="32px" height="32px" src="'+pic+'" data="'+pic+'"><div class="close">X</div></span>'); 
          }
        }else{
          artDialog.alert(data.msg);
        }
      },
      complete: function (XMLHttpRequest, textStatus) {
        $('.close').unbind().click(function(){
          $(this).parent().remove();
        }); 
        $('.dataImg').unbind().click(function(){
          if($('#viewImg').length>0){ 
            $('#viewImg').remove(); 
          } 
          $('body').append('<img id="viewImg" style="display:none" src="'+$(this).attr("src")+'">');
          $('#viewImg').on("load", function(){
            var w=$(this).width();
            var h=$(this).height();
            var l = w / h;
            if(h > handle.getScreenHeight() * 0.85){
              h = handle.getScreenHeight() * 0.85;
              w = h * l;
            }
            artDialog.alert2('<div style="width:'+w+'px;height:'+h+'px;"><img style="height:'+h+'px" src="'+$(this).attr("src")+'">') 
          }); 
        }); 
      } 
    },{
      data: {"mark": 0, "of": 0},
      uploadBtn: $('#uploadOverPicBtn'), 
      success: function (data, textStatus) {
        if(data.code==0){
          for(var o in data.data){
            var pic = data.data[o].original;
            $('#overPicSpan').html('<span style="position: relative;"><img class="dataImg" width="70px" height="70px" src="'+pic+'" data="'+pic+'"><div class="close">X</div></span>'); 
          }
        }else{
          artDialog.alert(data.msg);
        }
      },
      complete: function (XMLHttpRequest, textStatus) {
        $('.close').unbind().click(function(){
          $(this).parent().remove();
        }); 
        $('.dataImg').unbind().click(function(){
          if($('#viewImg').length>0){ 
            $('#viewImg').remove(); 
          } 
          $('body').append('<img id="viewImg" style="display:none" src="'+$(this).attr("src")+'">');
          $('#viewImg').on("load", function(){
            var w=$(this).width();
            var h=$(this).height();
            var l = w / h;
            if(h > handle.getScreenHeight() * 0.85){
              h = handle.getScreenHeight() * 0.85;
              w = h * l;
            }
            artDialog.alert2('<div style="width:'+w+'px;height:'+h+'px;"><img style="height:'+h+'px" src="'+$(this).attr("src")+'">') 
          }); 
        }); 
      } 
    }]
    },
    kindEditor: [{
      object: 'textarea[name=desc]',
      width: '100%',
      height: '600px',
      items: [
        'justifyleft', 'justifycenter', 'justifyright','justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
        'superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen', '/',
        'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
        'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image', 'multiimage', 'media',
        'hr', 'emoticons'
      ],
      afterCreate: function(obj){ 
        descEditor = obj; 
      } 
    }],
  });
  if(parentParams.parentNode.id == 0){
    $(".nameTr strong").text("分类名称：");
    $(".nameTr input[name=name]").attr("placeholder", "分类名称");
    $(".cateIconTr").remove();
  }else{
    $(".nameTr strong").text("图层名称：");
    $(".nameTr input[name=name]").attr("placeholder", "图层名称");
  }
  $("select[name=type]").on("change", function(){
    var val = $(this).val();
    $(".type1").hide();
    $(".type2").hide();
    $(".type3").hide();
    $(".type"+val).show();
  });
  $("select[name=type]").change();
  $("#editWarCategoryForm").validate({
    rules: {
      name: {
        required: true,
        zhengze: ".{2,20}"
      },
      icon: {
        required: true,
        zhengze: ".{2,300}"
      },
      parentId: {
        required: true
      }
    },
    messages: {
      name: {
        required: "必填",
        zhengze: "长度在2至20个字"
      },
      icon: {
        required: "必选",
        zhengze: "长度在2至300个字"
      },
      parentId: {
        required: "必选"
      }
    }
  });
  
  $("#saveBtn").click(function(){
    var flag = $("#editWarCategoryForm").valid();
    if(! flag) return;
    var data=$("#editWarCategoryForm").serializeArray();
    var params = {};
    $.each(data, function(i, field){
      var name = field.name;
      params[name] = field.value;
      console.log(name + "  " + field.value)
    });
    params['parentId'] = parentParams.parentNode.id;
    params['icon'] = $("#cateImgSpan img").attr("data");
    if(parentParams.parentNode.id != 0 && ! params.icon){
      artDialog.alert("菜单图片必须上传")
      return;
    }
    params['overIcon'] = $("#overImgSpan img").attr("data");
    if(params.type == 1) {
      var fields=new Array();
      var options=$("select[name=field] option");
      options.each(function(){
        fields.push($(this).text())
      });
      if(parentParams.parentNode.id != 0 && fields.length == 0){
        artDialog.alert("请设置字段")
        return;
      }
      params['fields'] = fields;
    }
    params["desc"]=descEditor.html();
    params.desc = params.desc.replace("<embed", "<video");
    console.log("params:" + JSON.stringify(params))
    $("#saveBtn").attr("disabled", true);
    $.ajax({
      contentType: "application/json",
      url: basePath+"warCategory/edit",
      data: JSON.stringify(params),
      type: 'post',
      dataType: 'json',
      success: function(res){
        if(res.code==0){
          parentParams.zTree.reAsyncChildNodes(parentParams.parentNode, "refresh", false, function(){
            var nodes = parentParams.zTree.getNodesByParam("name", params.name, parentParams.parentNode);
            parentParams.zTree.selectNode(nodes[0], false, true);
          });
          art.dialog.close();
        }else{
          artDialog.alert(res.msg)
        }
        $("#saveBtn").removeAttr("disabled");
      }
    });
  });
});